package org.offsync.rich
import java.nio.channels.Selector
import org.offsync.util._
import java.nio.channels.SelectableChannel

case class RichSelector(val selector: Selector) extends Disposable {
  override def disposeState = DisposeState.Unknown

  def select(deadline: Time): Int = {
    val nanoseconds = deadline.timeLeft match {
      case Forever => 0
      case DurationNanos(0) => 1
      case DurationNanos(n) => n
    }
    
    return selector.select(nanoseconds)
  }

  def onReady[Channel <: SelectableChannel](
      channel: Channel,
      readyOps: Int)(
          callback: Channel => Unit): Unit = {
    channel.register(selector, readyOps, { callback(channel) })
  }
  
  override def dispose(): Unit = selector.close()
  
  override def waitDisposed(
      deadline: Time): Unit = { }
}
